<?php

namespace app\common\service\organization;

use app\common\enums\AccountTypeEnum;
use app\common\enums\AppointmentStatusEnum;
use app\common\enums\BrokerageBusinessTypeEnum;
use app\common\enums\ClassHourBusinessTypeEnum;
use app\common\enums\ClassHourStatusEnum;
use app\common\enums\ClassHourTypeEnum;
use app\common\enums\LevelTypeEnum;
use app\common\model\banxi\core\CoreBrokerageRw;
use app\common\model\banxi\core\CoreClassHourDetail;
use app\common\model\banxi\core\CoreCourseAppointment;
use app\common\model\banxi\organization\Organization;
use app\common\model\banxi\organization\OrganizationLevelConfig;
use app\common\model\banxi\student\Student;
use app\common\service\ApiService;
use app\common\service\SnowflakeService;

class OrganizationRewardService extends ApiService
{
    //申请时明星校区经销商添加奖励课时
    public function campusFirstBuyReward($level, $organizationId)
    {
        // 获取等级配置信息
        $organizationLevelConfigModel = new OrganizationLevelConfig();
        $organizationLevelInfo = $organizationLevelConfigModel->where('id', $level)->find();
        if (empty($organizationLevelInfo)) {
            logSave([
                'receiverAccountId' => "被奖励机构：{$organizationId}",
                'levelId' => "等级Id：{$level}",
                'errorMsg' => '等级信息不存在'
            ], 'campusFirstBuyReward', 'organizationRewardLogs');
            //等级信息不存在
            return false;
        }
        $accountOpenReward = $organizationLevelInfo['accountOpenReward'];
        // 验证奖励课时数量
        if (!$accountOpenReward) {
            logSave([
                'receiverAccountId' => "被奖励机构：{$organizationId}",
                'levelId' => "等级Id：{$level}",
                'accountOpenReward' => "设置奖励课时：{$organizationLevelInfo['accountOpenReward']}",
                'errorMsg' => '该等级配置奖励课时为小于等于0的值'
            ], 'campusFirstBuyReward', 'organizationRewardLogs');
            return false;
        }
        // 获取被奖励机构信息
        $organization = Organization::where(['id' => $organizationId])->find();
        if (empty($organization)) {
            logSave([
                'receiverAccountId' => "被奖励机构：{$organizationId}",
                'levelId' => "等级Id：{$level}",
                'errorMsg' => '被奖励机构不存在'
            ], 'campusFirstBuyReward', 'organizationRewardLogs');
            //被奖励机构不存在
            return false;
        }
        // 初始化默认参数
        $payerAccountId = 0;
        $businessType = ClassHourBusinessTypeEnum::E7;
        $describe = '超级校区开户申请首购课时';
        $payerAccountType = AccountTypeEnum::PLATFORM;
        // 判断是否为合伙人入驻奖励
        if ($organizationLevelInfo['levelType'] == LevelTypeEnum::E2) {
            $rewardResult = $this->handlePartnerReward($organization, $organizationLevelInfo, $organizationId);
            if ($rewardResult === false) {
                return false;
            }
            // 更新参数
            $payerAccountId = $rewardResult['payerAccountId'];
            $businessType = $rewardResult['businessType'];
            $describe = $rewardResult['describe'];
            $payerAccountType = $rewardResult['payerAccountType'];
        }
        //明星校区经销商添加奖励课时
        $updateChange = [
            'classHourNum' => $accountOpenReward,
            'classHourType' => ClassHourTypeEnum::C_60,
            'payerAccountId' => $payerAccountId,
            'payerAccountType' => $payerAccountType,
            'receiverAccountId' => $organizationId,
            'receiverAccountType' => AccountTypeEnum::ORGAN,
            'businessType' => $businessType,
            'describe' => $describe,
            'status' => ClassHourStatusEnum::SUCCESS,
        ];
        $coreClassHourDetail = new CoreClassHourDetail();
        $coreClassHourDetail->updateAccountChange($updateChange, []);
        return true;
    }

    /**
     * 处理合伙人入驻奖励逻辑
     */
    private function handlePartnerReward($organization, $organizationLevelInfo, $organizationId)
    {
        $parentId = $organization['parentId'];
        $parentInfo = Organization::where(['id' => $parentId])->find();

        if (empty($parentInfo)) {
            logSave([
                'receiverAccountId' => "被奖励机构：{$organizationId}",
                'levelId' => "等级Id：{$organizationLevelInfo['id']}",
                'errorMsg' => '奖励机构的上级不存在'
            ], 'campusFirstBuyReward', 'organizationRewardLogs');
            return false;
        }

        $organizationLevelConfigModel = new OrganizationLevelConfig();
        $isCampus = $organizationLevelConfigModel->judgeLevelIdentity($parentInfo['level'], LevelTypeEnum::E1);

        if (!$isCampus) {
            logSave([
                'receiverAccountId' => "被奖励机构：{$organizationId}",
                'levelId' => "等级Id：{$organizationLevelInfo['id']}",
                'errorMsg' => '奖励机构的上级不是校区'
            ], 'campusFirstBuyReward', 'organizationRewardLogs');
            return false;
        }

        return [
            'payerAccountId' => $parentId,
            'businessType' => ClassHourBusinessTypeEnum::E10,
            'describe' => '合伙人入驻奖励',
            'payerAccountType' => AccountTypeEnum::ORGAN
        ];
    }

    //超级校区奖励邀请人
    public function invitationReward($parentId, $inviteId)
    {
        if ($parentId <= 0) {
            logSave([
                'inviteId' => "邀请人Id：{$inviteId}",
                'parentId' => "校区Id：{$parentId}",
                'errorMsg' => '所属校区为平台'
            ], 'invitationOccupancyReward', 'organizationRewardLogs');
            return false;
        }
        if ($inviteId <= 0) {
            logSave([
                'inviteId' => "邀请人Id：{$inviteId}",
                'parentId' => "校区Id：{$parentId}",
                'errorMsg' => '没有邀请人'
            ], 'invitationOccupancyReward', 'organizationRewardLogs');
            return false;
        }
        // 获取机构信息
        $organization = new organization();
        $parentInfo = $organization->where('id', $parentId)->find(); //校区信息
        if (empty($parentInfo)) {
            logSave([
                'inviteId' => "邀请人Id：{$inviteId}",
                'parentId' => "校区Id：{$parentId}",
                'errorMsg' => '校区信息不存在'
            ], 'invitationOccupancyReward', 'organizationRewardLogs');
            return false;
        }
        // 验证校区等级
        $organizationLevelConfigModel = new OrganizationLevelConfig();
        $isCampus = $organizationLevelConfigModel->judgeLevelIdentity($parentInfo['level'], LevelTypeEnum::E1);
        //是否是校区
        if (!$isCampus) {
            logSave([
                'inviteId' => "邀请人Id：{$inviteId}",
                'parentId' => "校区Id：{$parentId}",
                'errorMsg' => '校区信息等级不属于校区'
            ], 'invitationOccupancyReward', 'organizationRewardLogs');
            return false;
        }
        $inviteInfo = $organization->where('id', $inviteId)->find(); //校区信息
        if (empty($inviteInfo)) {
            logSave([
                'inviteId' => "邀请人Id：{$inviteId}",
                'parentId' => "校区Id：{$parentId}",
                'errorMsg' => '邀请人信息不存在'
            ], 'invitationOccupancyReward', 'organizationRewardLogs');
            return false;
        }
        //获取奖励课时
        $organizationLevelConfigModel = new OrganizationLevelConfig();
        $inviteReward = $organizationLevelConfigModel->getLevelConfig($inviteInfo['level'], 'inviteReward');
        if (!$inviteReward) {
            logSave([
                'inviteId' => "邀请人Id：{$inviteId}",
                'parentId' => "校区Id：{$parentId}",
                'partnerInviteReward' => "邀请人奖励课时：{$inviteReward}",
                'errorMsg' => '邀请人奖励课时错误'
            ], 'invitationOccupancyReward', 'organizationRewardLogs');
            return false;
        }
        $updateChangeInvite = [
            'classHourNum' => $inviteReward,
            'classHourType' => ClassHourTypeEnum::C_60,
            'payerAccountId' => $parentId,
            'payerAccountType' => AccountTypeEnum::ORGAN,
            'receiverAccountId' => $inviteId,
            'receiverAccountType' => AccountTypeEnum::ORGAN,
            'businessType' => ClassHourBusinessTypeEnum::E9,
            'describe' => '邀请奖励,邀请机构：' . $inviteId,
            'status' => ClassHourStatusEnum::SUCCESS,
        ];
        $coreClassHourDetail = new CoreClassHourDetail();
        $coreClassHourDetail->updateAccountChange($updateChangeInvite, []);
        return true;
    }

    //校区邀请校区的复购奖励
    public function accompanyServiceReward($recharge)
    {
        // 获取机构信息
        $organizationId = $recharge['organizationId'];
        $classHourType = $recharge['classHourType'];
        // 验证课时类型
        if ($classHourType != ClassHourTypeEnum::C_60) {
            $classHourTypeMsg = (new ClassHourTypeEnum())->getDescription($classHourType);
            logSave([
                'recharge' => $recharge,
                'classHourType' => "课时类型：{$classHourType}",
                'classHourTypeMsg' => "课时类型：{$classHourTypeMsg}",
                'errorMsg' => '课时类型不符合要求'
            ], 'accompanyingServiceReward', 'organizationRewardLogs');
            return false;
        }
        $organization = Organization::where(['id' => $organizationId])->find();
        if (empty($organization)) {
            logSave([
                'recharge' => $recharge,
                'errorMsg' => '充值机构信息不存在'
            ], 'accompanyingServiceReward', 'organizationRewardLogs');
            return false;
        }

        // 获取并验证邀请人信息
        $receiverAccountId = $organization['inviteId'];
        if (!$receiverAccountId) {
            logSave([
                'recharge' => $recharge,
                'receiverAccountId' => "被邀请人Id：{$receiverAccountId}",
                'errorMsg' => '没有设置邀请人'
            ], 'accompanyingServiceReward', 'organizationRewardLogs');
            return false;
        }
        // 验证邀请人和当前机构是否都是校区
        $inviterOrganization = Organization::where(['id' => $organization['inviteId']])->find();
        if (empty($inviterOrganization)) {
            logSave([
                'recharge' => $recharge,
                'errorMsg' => '邀请机构信息不存在'
            ], 'accompanyingServiceReward', 'organizationRewardLogs');
            return false;
        }

        $organizationLevelConfigModel = new OrganizationLevelConfig();
        $inviteLevel = $organizationLevelConfigModel->judgeLevelIdentity($inviterOrganization['level'], LevelTypeEnum::E1); // 邀请人是否是校区
        $organizationLevel = $organizationLevelConfigModel->judgeLevelIdentity($organization['level'], LevelTypeEnum::E1); // 当前充值机构是否是校区

        if (!$inviteLevel || !$organizationLevel) {
            logSave([
                'recharge' => $recharge,
                'inviteLevel' => "邀请机构等级：{$inviterOrganization['level']}",
                'rechargeLevel' => "充值机构等级：{$organization['level']}",
                'errorMsg' => '都不是校区等级'
            ], 'accompanyingServiceReward', 'organizationRewardLogs');
            return false;
        }

        // 计算奖励课时数
        $classHourNum = $recharge['classHourNum'];
        $accompanyReward = $organizationLevelConfigModel->getLevelConfig($organization['level'], 'accompanyReward');
        if (!$accompanyReward) {
            logSave([
                'recharge' => $recharge,
                'levelId' => $organization['level'],
                'accompanyReward' => "配置的陪跑复购奖励：{$accompanyReward}",
                'errorMsg' => '陪跑复购奖励设置错误'
            ], 'accompanyingServiceReward', 'organizationRewardLogs');
            return false;
        }

        $accompanyRewardRate = bcdiv($accompanyReward, 100, 2);
        $rewardClassHourNum = bcmul($classHourNum, $accompanyRewardRate, 0); // 充值复购奖励课时

        // 验证奖励课时数
        if ($rewardClassHourNum <= 0) {
            logSave([
                'recharge' => $recharge,
                'rewardClassHourNum' => "复购奖励邀请课时数：{$rewardClassHourNum}",
                'errorMsg' => '复购奖励课时数错误'
            ], 'accompanyingServiceReward', 'organizationRewardLogs');
            return false;
        }


        // 发放复购奖励
        $updateChange = [
            'classHourNum' => $rewardClassHourNum,
            'classHourType' => $classHourType,
            'payerAccountId' => 0,
            'payerAccountType' => AccountTypeEnum::PLATFORM,
            'receiverAccountId' => $receiverAccountId,
            'receiverAccountType' => AccountTypeEnum::ORGAN,
            'businessType' => ClassHourBusinessTypeEnum::E8,
            'describe' => '校区邀请校区复购奖励,课时数:' . $classHourNum . ',奖励比例：' . $accompanyReward . "%",
            'status' => ClassHourStatusEnum::SUCCESS
        ];

        $coreClassHourDetail = new CoreClassHourDetail();
        $coreClassHourDetail->updateAccountChange($updateChange, []);
        return true;
    }


    //陪跑奖励
    public function companionRunReward($studentId, $appointmentId)
    {
        $studentInfo = Student::getUserInfo($studentId);
        if (empty($studentInfo)) {
            logSave([
                'studentId' => $studentId,
                'errorMsg' => '学生信息不存在'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }
        $studentOrgInfo = Organization::where(['id' => $studentInfo['organizationId']])->find();
        // 验证预约信息
        if (empty($studentOrgInfo)) {
            logSave([
                'appointmentId' => $appointmentId,
                'studentId' => $studentId,
                'studentOrgId' => $studentInfo['organizationId'],
                'errorMsg' => '学生机构不存在'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }
        if (empty($studentOrgInfo['accompanyId'])) {
            logSave([
                'appointmentId' => $appointmentId,
                'studentId' => $studentId,
                'studentOrgId' => $studentInfo['organizationId'],
                'errorMsg' => '学生机构没有设置陪跑机构'
            ], 'companionRunningReward', 'organizationRewardLogs');
        }
        $accompanyInfo = $organizationInfo = Organization::where(['id' => $studentOrgInfo['accompanyId']])->find();
        // 验证机构信息
        if (empty($accompanyInfo)) {
            logSave([
                'appointmentId' => $appointmentId,
                'studentId' => $studentId,
                'studentOrgId' => $studentInfo['organizationId'],
                'errorMsg' => '陪跑机构不存在'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }
        if (!$accompanyInfo['level']) {
            logSave([
                'appointmentId' => $appointmentId,
                'studentId' => $studentId,
                'studentOrgId' => $studentInfo['organizationId'],
                'errorMsg' => '陪跑机构等级错误'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }
        $CoreCourseAppointmentModel = new CoreCourseAppointment();
        // 获取预约信息
        $appointment = $CoreCourseAppointmentModel->where('id', $appointmentId)->find();
        if (!$appointment) {
            logSave([
                'appointmentId' => $appointmentId,
                'studentId' => $studentId,
                'studentOrgId' => $studentInfo['organizationId'],
                'errorMsg' => '排课预约不存在'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return true;
        }

        // 验证预约状态
        $appointmentStatus = $appointment['appointmentStatus'];
        if ($appointmentStatus != AppointmentStatusEnum::END) {
            $appointmentStatusMsg = (new AppointmentStatusEnum())->getDescription($appointmentStatus);
            logSave([
                'appointmentId' => $appointmentId,
                'studentId' => $studentId,
                'studentOrgId' => $studentInfo['organizationId'],
                'appointmentStatus' => "预约状态：{$appointmentStatus}",
                'appointmentStatusMsg' => "预约状态：{$appointmentStatusMsg}",
                'errorMsg' => '该预约状态不符合要求'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return true;
        }

        // 验证陪跑奖励开关
        $isCompanionRunReward = $organizationInfo['isCompanionRunReward'];
        if (!$isCompanionRunReward) {
            logSave([
                'appointmentId' => $appointmentId,
                'studentId' => $studentId,
                'studentOrgId' => $studentInfo['organizationId'],
                'organizationInfo' => $organizationInfo,
                'isCompanionRunReward' => "机构陪跑奖励开关：{$isCompanionRunReward}",
                'errorMsg' => '该机构陪跑奖励未开启'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }

        // 获取陪跑奖励配置
        $organizationLevelConfigModel = new OrganizationLevelConfig();
        $companyRunReward = $organizationLevelConfigModel->getLevelConfig($organizationInfo['level'], 'companyRunReward');
        if (!$companyRunReward) {
            logSave([
                'appointmentId' => $appointmentId,
                'studentId' => $studentId,
                'studentOrgId' => $studentInfo['organizationId'],
                'companyRunReward' => "机构陪跑奖励比例：{$companyRunReward}",
                'errorMsg' => "该机构陪跑奖励比例设置为{$companyRunReward}"
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }

        // 生成奖励流水ID
        $snowflakeService = new SnowflakeService(1, 1);
        $brokerageFlowId = $snowflakeService->nextId();

        // 准备奖励数据
        $organizationId = $organizationInfo['id'];
        // 发放陪跑奖励
        $coreBrokerageRwModel = new CoreBrokerageRw();
        $describe = "获得「{$studentOrgInfo['name']}】旗下学员 [{$studentInfo['name']}]课消陪跑奖励 ¥{$companyRunReward}";
        $coreBrokerageRwModel->updateAccount([
            'id' => $brokerageFlowId,
            'accountId' => $organizationId,
            'accountType' => AccountTypeEnum::ORGAN,
            'organizationId' => $organizationId,
            'businessType' => BrokerageBusinessTypeEnum::E4,
            'businessId' => $appointmentId,
            'value' => $companyRunReward,
            'describe' => $describe
        ]);
        $appointment['brokerageFlowId'] = $brokerageFlowId;
        $appointment->save();
        return true;
    }

    //陪跑奖励退回
    public function companionRunRewardRefund($organizationInfo, $coreCourseAppointmentInfo)
    {
        if (empty($coreCourseAppointmentInfo)) {
            logSave([
                'coreCourseAppointmentInfo' => $coreCourseAppointmentInfo,
                'organizationInfo' => $organizationInfo,
                'errorMsg' => '该预约不存在'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }
        $brokerageFlowId = $coreCourseAppointmentInfo['brokerageFlowId'];
        if (empty($brokerageFlowId)) {
            logSave([
                'coreCourseAppointmentInfo' => $coreCourseAppointmentInfo,
                'organizationInfo' => $organizationInfo,
                'errorMsg' => '该预约没有陪跑奖励'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }
        $appointmentStatus = $coreCourseAppointmentInfo['appointmentStatus'];
        if (!in_array($appointmentStatus, [AppointmentStatusEnum::PENDING_CLASS, AppointmentStatusEnum::EXPIRED, AppointmentStatusEnum::CANCEL])) {
            $appointmentStatusMsg = (new AppointmentStatusEnum())->getDescription($appointmentStatus);
            logSave([
                'coreCourseAppointmentInfo' => $coreCourseAppointmentInfo,
                'appointmentStatus' => "预约状态：{$appointmentStatus}",
                'appointmentStatusMsg' => "预约状态：{$appointmentStatusMsg}",
                'organizationInfo' => $organizationInfo,
                'errorMsg' => '该预约状态不符合要求'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }
        if (empty($organization)) {
            logSave([
                'coreCourseAppointmentInfo' => $coreCourseAppointmentInfo,
                'organizationInfo' => $organizationInfo,
                'errorMsg' => '该机构不存在'
            ], 'companionRunningReward', 'organizationRewardLogs');
            return false;
        }
        $coreBrokerageRw = new CoreBrokerageRw();
        $coreBrokerageRw->accompanyrefundAccount($brokerageFlowId, '取消预约退回陪跑金额');
        return true;
    }
}
